package com.zr.gdms.daoimpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.zr.gdms.dao.FuncDao;
import com.zr.gdms.model.Function;
import com.zr.gdms.util.JDBCUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 功能逻辑实现层接口
 * @author 李培宁
 *
 */
public class FuncDaoImpl implements FuncDao{

	@Override
	public JSONArray getFuncsByPid(int pid) {
		JSONArray funcs = new JSONArray();
		StringBuffer sql = new StringBuffer("");
		sql.append(" SELECT `function`.fid,`function`.fname,`function`.fpage,`function`.fstate,`function`.furl,`function`.pid FROM `function`");
		
		sql.append(" WHERE `function`.pid=?");
		Connection con = JDBCUtil.getConnection();
		try {
			PreparedStatement pst = con.prepareStatement(sql.toString());
			pst.setInt(1, pid);
		
			ResultSet rs = pst.executeQuery();

			while (rs.next()) {
				JSONObject func = new JSONObject();
				func.put("id", rs.getInt("fid"));
				func.put("text", rs.getString("fname"));
				func.put("state", rs.getString("fstate"));
				JSONObject attr = new JSONObject();
				attr.put("furl", rs.getString("furl"));
				func.put("attributes", attr);
				funcs.add(func);
			}
			JDBCUtil.closeJDBC(pst, con);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return funcs;
	}

	@Override
	public JSONArray getCurrentUserFuncs(int pid) {
		JSONArray userfuncs = this.getFuncsByPid(pid);
		for (int i = 0; i < userfuncs.size(); i++) {
			String state = userfuncs.getJSONObject(i).getString("state");
			if ("open".equals(state)) {
				continue;
			} else {
				int currentId = userfuncs.getJSONObject(i).getInt("id");
				JSONArray children = this.getCurrentUserFuncs(currentId);
				userfuncs.getJSONObject(i).put("children", children);
				
			}
		}
		return userfuncs;
	}

	@Override
	public List<Function> getFunctionByUserFid(int fid) {
		List<Function> functions = new ArrayList<Function>();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT *FROM `function`");
		sql.append(" INNER JOIN `user`");
		sql.append(" ON `function`.fid = `user`.fid");
		sql.append(" WHERE `user`.fid = ?");
		Connection con = JDBCUtil.getConnection();
		try {
			PreparedStatement pst=con.prepareStatement(sql.toString());
			pst.setInt(1, fid);
			ResultSet rs = pst.executeQuery();
			while (rs.next()) {
				Function f = new Function();
				f.setFid(rs.getInt("fid"));
				f.setFname(rs.getString("fname"));
				f.setFpage(rs.getString("fpage"));
				f.setFstate(rs.getString("fstate"));
				f.setFurl(rs.getString("furl"));
				f.setPid(rs.getInt("pid"));
				functions.add(f);
			}
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return functions;
	}

}
